using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using Core;
using Frontends.Nodes;

namespace Frontends.Controller
{
    public class ToDoItemTreeController
    {
        private TreeView _tree;
        private IDictionary<Guid, ToDoItemTreeNode> _nodes;
        private object _syncRoot;
        private ToDoPersonalManager _manager;
        private ToDoItemRootNode _rootNode;   


        public ToDoItemTreeController(TreeView tree, ToDoPersonalManager manager)
        {
            _tree = tree;
            _manager = manager;
            _syncRoot = new object();
            _nodes = new Dictionary<Guid, ToDoItemTreeNode>();
        }

        public void AddNode(ToDoItemTreeNode node, Guid parentNode)
        {
            lock (_syncRoot)
            {
                if (_nodes.ContainsKey(node.Item.Id) == false)
                {
                    _nodes.Add(node.Item.Id, node);
                }
            }
            if (parentNode == Guid.Empty)
            {
                _rootNode.Nodes.Add(node);
            }
            else
            {
                _nodes[parentNode].Nodes.Add(node);
            }
        }

        public void RemoveNode(ToDoItemTreeNode node)
        {
            RemoveNode(node.Item.Id);
        }

        public void RemoveNode(Guid itemId)
        {
            lock (_syncRoot)
            {
                _nodes.Remove(itemId);
            }
        }

        public void Initialize()
        {
            Guid rootId = _manager.Persistence.GetRootElementId("crauscher");
            _rootNode = new ToDoItemRootNode(rootId, "crauscher");
            _tree.Nodes.Add(_rootNode);
        }
    }
}
